<?php
class indexController extends Controller {

	private $table = "user";
	
	public function initialize() {
		$this->view->title = 'Schagen - Login';
		$this->view->layoutPath = 'template';
		$this->view->templateUrl = 'template';
		$this->view->add_css('back/back-main.css');
		$this->view->add_css('back/login.css');
		$this->view->add_js('jquery-min.js');
	}

	public function indexAction() {
		
		if(isset($_GET['logout']) && $_GET['logout'] == "true"){
			$this->logout();
			return;
		}
		
		if( !isset( $_SESSION['username'] ) ){

			if( isset( $_POST['submit'] ) && isset( $_POST['username'] ) && isset( $_POST['userpass'] )){
				
				$username = $_POST['username'];
				$password = $_POST['userpass'];

				$MD5password = md5($password); // hash the password so we can compare to DB	

				$sql = "username='".$username."' AND password='".$MD5password."'"; 
				// only one user can exist so LIMIT will always be one	
				//query the DB for the username
				$result = DBH::getInstance()->read( $sql, $this->table );
	
				if( isset($result->password) && $MD5password == $result->password ){ /// are they a valid user
					
					$query = "`id` = " . $result->groups_id;
					$admingroup = DBH::getInstance()->read($query, "groups"); //check if user belongs to administrator group


					$_SESSION['loggedin'] = "true";
					$_SESSION['userId'] = $result->id; 
					$_SESSION['username'] = $result->username;
					$_SESSION['isAdmin']  = $admingroup->admin;
					$_SESSION['groupId'] = $result->groups_id;
					
				$location =	header("Location: ./administrator");
				}else{
					$this->view->error = "true";
				}
			}
			}else{
				$location = header('Location: ./administrator');
				$this->view->show();
			}	
			$location;
		$this->view->setLayout('login');
		$this->view->show();
	}
	
	public function logout(){
		unset($_SESSION['loggdin']);
		unset($_SESSION['userId']);
		unset($_SESSION['username']);
		unset($_SESSION['isAdmin']);
		header('Location: ./');
		$this->view->show();
	}
}